package com.bfl.sa.common.service;

import com.bfl.sa.common.entity.AbstractEntity;
import com.bfl.sa.common.entity.search.Searchable;
import com.bfl.sa.common.mapper.BaseMapper;
import com.bfl.sa.common.mybatis.entity.Query;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.data.domain.Pageable;

import java.io.Serializable;
import java.util.List;

public abstract class AbstractService<E extends AbstractEntity, K extends Serializable, M extends BaseMapper<E, K>> {

    protected M baseMapper;

    public E save(E entity) {
        if (entity.getId() == null) {
            baseMapper.insert(entity);
        } else {
            baseMapper.update(entity);
        }
        return entity;
    }

    public E insert(E entity) {
        baseMapper.insert(entity);
        return entity;
    }

    public E update(E entity) {
        baseMapper.update(entity);
        return entity;
    }

    public void delete(K id) {
        baseMapper.delete(id);
    }

    public void delete(K[] ids) {
        baseMapper.batchDelete(ids);
    }

    public E findOne(K id) {
        return baseMapper.selectOne(id);
    }

    public Page<E> findPage(Searchable searchable) {
        Query query = Query.newQuery(searchable);
        return PageHelper.startPage(query).doSelectPage(() -> baseMapper.selectList(query));
    }

    public Page<E> findPage(Pageable pageable) {
        Query query = Query.newQuery(pageable);
        return PageHelper.startPage(query).doSelectPage(() -> baseMapper.selectList(query));
    }

    public List<E> findList() {
        return baseMapper.selectList(Query.newQuery());
    }

    public List<E> findList(Searchable searchable) {
        return baseMapper.selectList(Query.newQuery(searchable));
    }

    public int count(Searchable searchable) {
        return baseMapper.count(Query.newQuery(searchable));
    }

    public boolean exists(K id) {
        return baseMapper.count(Query.newQuery("id", id)) > 0;
    }
}
